// componentmanager.cpp : defines a class that manages and registers components, and provides a factory for their creation
//$Id: ComponentManager.cpp 16 2009-08-14 17:38:36Z brwarner2 $

#include "StdAfx.h"
#include "ComponentManager.h"

CComponentManager::CComponentManager(void) : m_registeredComponents()
{
}

void CComponentManager::Register( Factory f, Destruct d, Reg r, ComponentID id )
{
	//Construct a component entry
	ComponentEntry entry = { f, d, r, id };

	//Insert it into the array
	m_registeredComponents[id] = entry;
}

IComponent* CComponentManager::Create( ComponentID id )
{
	//Get component entry structure
	ComponentDB::iterator iter = m_registeredComponents.find(id);
	if( iter == m_registeredComponents.end() ) return 0;

	//Create a component
	IComponent* c = iter->second.create();
	if(c == 0) return 0;

	//Store it
	m_components.push_back(c);

	//Return it
	return c;
}

void CComponentManager::Destroy( IComponent*& c, bool bClear )
{
	//Get component entry structure
	ComponentDB::iterator iter = m_registeredComponents.find(c->GetComponentID());
	if( iter == m_registeredComponents.end() ) return;

	//Remove from our list
	if(bClear) {
		std::list<IComponent*>::iterator iter2 = std::find( m_components.begin(), m_components.end(), c );
		if( iter2 == m_components.end() ) return;
		m_components.erase(iter2);
	}

	//Destroy component
	iter->second.destroy(c);
	c = 0;
}

CComponentManager::~CComponentManager(void)
{
	//Destroy all components that we own
	std::for_each( m_components.begin(), m_components.end(), boost::bind(&CComponentManager::Destroy, this, _1, false) );
	m_components.clear();

	//Clear database
	m_registeredComponents.clear();
}

void CComponentManager::RegisterGM( gmMachine* pGM )
{
	//For each registered component, call register GM
	ComponentDB::iterator iter = m_registeredComponents.begin();
	for(; iter != m_registeredComponents.end(); iter++)
	{
		iter->second.reg( pGM );
	}
}